<?php

namespace controller\admin;

defined('IA_ROOT') || exit();

use facade\Model;
use facade\View;
use facade\Util;

// 评论管理
class Comment extends Base
{
    // 列表
    public function index()
    {
        if (Util::isAjax()) {
            $param = Util::param();
            $start = ($param['page'] - 1) * $param['limit'];
            $limit = $param['limit'];
            $where = "";
            // 搜索
            if (!empty($param['search'])) {
                foreach ((array)$param['search'] as $k => $v) {
                    if (strlen($v)) {
                        if ($k = 'article_id') {
                            if ($v)
                                $where .= " AND `$k` = '$v'";
                        } else if ($k == 'status') {
                            $where .= " AND `$k` = '$v'";
                        } else if (in_array($k, ['start', 'end'])) {
                            $timestamp = strtotime($v);
                            if ($k == 'start')
                                $where .= " AND `time` >= '$timestamp'";
                            else
                                $where .= " AND `time` <= '$timestamp'";
                        } else {
                            $where .= " AND `$k` like '%{$v}%'";
                        }
                    }
                }
            }
            $count = Model::fetchColumn("SELECT COUNT(*) FROM `comment` WHERE 1=1 $where AND `pid` = 0 AND `status` IN (0, 1, 2) ORDER BY `sort` DESC, `id` DESC");
            $data = Model::fetchAll("SELECT * FROM `comment` WHERE 1=1 $where AND `pid` = 0 AND `status` IN (0, 1, 2) ORDER BY `sort` DESC, `id` DESC LIMIT $start, $limit");
            $ids = array_map(function ($item) {
                return $item['id'];
            }, $data);
            $idStr = implode(',', $ids);
            if ($idStr) {
                $childs = Model::fetchAll("SELECT * FROM `comment` WHERE 1=1 $where AND `pid` IN ($idStr) AND `status` IN (0, 1, 2) ORDER BY `sort` DESC, `id` DESC");
                $data = array_merge($data, $childs);
            }
            $data = $this->format_tree($data, 'comment');
            $article_ids = array_map(function ($item) {
                return $item['article_id'];
            }, $data);
            $idStr = $article_ids ? implode(',', $article_ids) : 0;
            $article = Model::fetchAll("SELECT `id`, `title`, `slug`, `lang` FROM `article` WHERE `id` IN ($idStr)");
            $article = Util::formatKey($article);
            if ($count) {
                $res['code'] = 0;
            } else {
                $res['code'] = 1;
                $res['msg'] = Util::tran('暂无记录');
            }
            $res['count'] = $count;
            $res['data'] = array_map(function ($item) use ($article) {
                $item['tree_comment'] = mb_strimwidth(preg_replace('/\s+/sim', ' ', strip_tags($item['tree_comment'])), 0, 140, '...', 'UTF-8');
                $item['article_title'] = $article[$item['article_id']]['title'];
                $item['article_link'] = $this->base_url . ($article[$item['article_id']]['lang'] == 'zh-CN' ? '/' : "/{$this->lang}/") . ($article[$item['article_id']]['slug'] ? $article[$item['article_id']]['slug'] : $article[$item['article_id']]['id']) . '.html';
                $item['time'] = date('Y-m-d H:i', $item['time']);
                $item['action'] = 'index';
                return $item;
            }, $data);
            exit(json_encode($res));
        }
        View::assign('action', 'index');
        View::assign('tran', [
            'article' => Util::tran('文章'),
            'input' => Util::tran('请输入'),
            'choose' => Util::tran('请选择'),
            'comment_author' => Util::tran('评论作者'),
            'comment_content' => Util::tran('评论内容'),
            'status' => Util::tran('状态'),
            'normal' => Util::tran('正常'),
            'pending' => Util::tran('待审'),
            'spam' => Util::tran('垃圾评论'),
            'date' => Util::tran('日期'),
            'delall' => Util::tran('批量删除'),
            'refresh' => Util::tran('刷新'),
            'approve' => Util::tran('通过'),
            'rubbish' => Util::tran('垃圾'),
            'comment_list' => Util::tran('评论列表'),
            'author' => Util::tran('作者'),
            'rebot' => Util::tran('机器人'),
            'comment_article' => Util::tran('评论文章'),
            'sort' => Util::tran('排序'),
            'robot_comment' => Util::tran('机器人评论'),
            'time' => Util::tran('时间'),
            'option' => Util::tran('操作'),
            'reply' => Util::tran('回复'),
            'edit' => Util::tran('编辑'),
            'delete' => Util::tran('删除'),
        ]);
        View::display('admin/comment/index.html');
    }

    // 机器人评论列表
    public function robot()
    {
        if (Util::isAjax()) {
            $param = Util::param();
            $start = ($param['page'] - 1) * $param['limit'];
            $limit = $param['limit'];
            $where = "";
            // 搜索
            if (!empty($param['search'])) {
                foreach ((array)$param['search'] as $k => $v) {
                    if (strlen($v)) {
                        if ($k = 'article_id') {
                            if ($v)
                                $where .= " AND `$k` = '$v'";
                        } else if ($k == 'status') {
                            $where .= " AND `$k` = '$v'";
                        } else if (in_array($k, ['start', 'end'])) {
                            $timestamp = strtotime($v);
                            if ($k == 'start')
                                $where .= " AND `time` >= '$timestamp'";
                            else
                                $where .= " AND `time` <= '$timestamp'";
                        } else {
                            $where .= " AND `$k` like '%{$v}%'";
                        }
                    }
                }
            }
            $count = Model::fetchColumn("SELECT COUNT(*) FROM `comment` WHERE 1=1 $where AND `pid` = 0 AND `status`=3 ORDER BY `sort` DESC, `id` DESC");
            $data = Model::fetchAll("SELECT * FROM `comment` WHERE 1=1 $where AND `pid` = 0 AND `status`=3 ORDER BY `sort` DESC, `id` DESC LIMIT $start, $limit");
            $ids = array_map(function ($item) {
                return $item['id'];
            }, $data);
            $idStr = implode(',', $ids);
            if ($idStr) {
                $childs = Model::fetchAll("SELECT * FROM `comment` WHERE 1=1 $where AND `pid` IN ($idStr) AND `status` IN (0, 1, 2) ORDER BY `sort` DESC, `id` DESC");
                $data = array_merge($data, $childs);
            }
            $data = $this->format_tree($data, 'comment');
            $article_ids = array_map(function ($item) {
                return $item['article_id'];
            }, $data);
            $idStr = $article_ids ? implode(',', $article_ids) : 0;
            $article = Model::fetchAll("SELECT `id`, `title`, `slug`, `lang` FROM `article` WHERE `id` IN ($idStr)");
            $article = Util::formatKey($article);
            if ($count) {
                $res['code'] = 0;
            } else {
                $res['code'] = 1;
                $res['msg'] = Util::tran('暂无记录');
            }
            $res['count'] = $count;
            $res['data'] = array_map(function ($item) use ($article) {
                $item['tree_comment'] = mb_strimwidth(preg_replace('/\s+/sim', ' ', strip_tags($item['tree_comment'])), 0, 140, '...', 'UTF-8');
                $item['article_title'] = $article[$item['article_id']]['title'];
                $item['article_link'] = $this->base_url . ($article[$item['article_id']]['lang'] == 'zh-CN' ? '/' : "/{$this->lang}/") . ($article[$item['article_id']]['slug'] ? $article[$item['article_id']]['slug'] : $article[$item['article_id']]['id']) . '.html';
                $item['time'] = date('Y-m-d H:i', $item['time']);
                $item['action'] = 'robot';
                return $item;
            }, $data);
            exit(json_encode($res));
        }
        View::assign('action', 'robot');
        View::assign('tran', [
            'article' => Util::tran('文章'),
            'input' => Util::tran('请输入'),
            'comment_author' => Util::tran('评论作者'),
            'comment_content' => Util::tran('评论内容'),
            'status' => Util::tran('状态'),
            'normal' => Util::tran('正常'),
            'pending' => Util::tran('待审'),
            'spam' => Util::tran('垃圾评论'),
            'date' => Util::tran('日期'),
            'delall' => Util::tran('批量删除'),
            'refresh' => Util::tran('刷新'),
            'approve' => Util::tran('通过'),
            'rubbish' => Util::tran('垃圾'),
            'comment_list' => Util::tran('评论列表'),
            'author' => Util::tran('作者'),
            'rebot' => Util::tran('机器人'),
            'comment_article' => Util::tran('评论文章'),
            'sort' => Util::tran('排序'),
            'robot_comment' => Util::tran('机器人评论'),
            'time' => Util::tran('时间'),
            'option' => Util::tran('操作'),
            'reply' => Util::tran('回复'),
            'edit' => Util::tran('编辑'),
            'delete' => Util::tran('删除'),
        ]);
        View::display('admin/comment/index.html');
    }

    // 回复
    public function reply()
    {
        $id = (int)Util::param('id');
        $row = Model::fetch("SELECT * FROM `comment` WHERE `id`=:id", [':id' => $id]);
        (!$row || $row['pid']) && Util::errMsg('ID ' . Util::tran('错误'));

        View::assign('row', $row);
        View::assign('tran', [
            'comment_author' => Util::tran('评论作者'),
            'input_comment_author' => Util::tran('请输入评论作者'),
            'comment_content' => Util::tran('评论内容'),
            'reply_content' => Util::tran('回复内容'),
            'save' => Util::tran('保存'),
            'reset' => Util::tran('重置'),
        ]);
        View::display('admin/comment/reply.html');
    }

    // 保存
    public function save_reply()
    {
        $param = Util::param(['pid', 'comment']);
        $row = Model::fetch("SELECT * FROM `comment` WHERE `id`=:pid ORDER BY `id`", [':pid' => $param['pid']]);
        !$row && Util::errMsg(Util::tran('回复ID错误'));
        empty($param['comment']) && Util::errMsg(Util::tran('回复评论为空'));

        // 写入数据库记录日志
        $param['article_id'] = $row['article_id'];
        $param['author'] = $this->user['username'];
        $param['time'] = time();
        if (preg_match_all('#<[^>]*=["\']([^"\']*/static/upload/.+?\.[^"\']*)["\'][^>]*>#i', $param['comment'], $matches)) {
            foreach ($matches[1] as $match) {
                $param['comment'] = str_replace($match, str_replace($this->base_url, '', $match), $param['comment']);
            }
        }
        if (preg_match_all('#<[^>]*=["\']([^"\']*/static/res/.+?\.[^"\']*)["\'][^>]*>#i', $param['comment'], $matches)) {
            foreach ($matches[1] as $match) {
                $param['comment'] = str_replace($match, str_replace($this->base_url, '', $match), $param['comment']);
            }
        }
        $lastInsertId = Model::insert('comment', $param);
        if ($lastInsertId) {
            // 修改媒体状态
            $paths = [0 => [], 2 => []];
            if (preg_match_all('#<[^>]*=["\']([^"\']*/static/upload/.+?\.[^"\']*)["\'][^>]*>#i', $param['comment'], $matches)) {
                foreach ($matches[1] as $match) {
                    if (is_file(IA_ROOT . str_replace($this->base_url, '', $match)))
                        $paths[0][] = str_replace($this->base_url, '', $match);
                    else
                        $paths[2][] = str_replace($this->base_url, '', $match);
                }
            }
            $paths[0] && Model::update('media', ['status' => 0], ['path' => $paths[0]]);
            $paths[2] && Model::update('media', ['status' => 2], ['path' => $paths[2]]);
            // 清除文章缓存
            $this->clearCache($row['article_id']);
            $this->log(Util::tran('回复评论'), Util::tran('回复评论') . " @{$row['author']} " . Util::tran('成功'), 0);
            Util::errMsg(['code' => 0, 'msg' => Util::tran('回复评论成功')]);
        } else {
            $this->log(Util::tran('回复评论'), Util::tran('回复评论') . " @{$row['author']} " . Util::tran('失败'), 1);
            Util::errMsg(['code' => 1, 'msg' => Util::tran('回复评论失败')]);
        }
    }

    // 编辑
    public function edit($id = 0)
    {
        $row = Model::fetch("SELECT * FROM `comment` WHERE `id`=:id", [':id' => $id]);
        !$row && Util::errMsg('ID ' . Util::tran('错误'));
        View::assign('row', $row);
        View::assign('tran', [
            'comment_author' => Util::tran('评论作者'),
            'input_comment_author' => Util::tran('请输入评论作者'),
            'comment_content' => Util::tran('评论内容'),
            'sort' => Util::tran('排序'),
            'status' => Util::tran('状态'),
            'choose' => Util::tran('请选择'),
            'input_sort' => Util::tran('请输入排序'),
            'normal' => Util::tran('正常'),
            'pending' => Util::tran('待审'),
            'spam_comment' => Util::tran('垃圾评论'),
            'save' => Util::tran('保存'),
            'reset' => Util::tran('重置'),
        ]);
        View::display('admin/comment/edit.html');
    }

    // 更新
    public function update()
    {
        $param = Util::param(['id', 'author', 'comment', 'sort', 'status']);
        $row = Model::fetch("SELECT * FROM `comment` WHERE `id`=:id", [':id' => $param['id']]);
        !$row && Util::errMsg('ID ' . Util::tran('错误'));
        empty($param['comment']) && Util::errMsg(Util::tran('评论内容为空'));
        !is_numeric($param['sort']) && Util::errMsg(Util::tran('排序只能是数字'));

        // 更新数据库记录日志
        if (preg_match_all('#<[^>]*=["\']([^"\']*/static/upload/.+?\.[^"\']*)["\'][^>]*>#i', $param['comment'], $matches)) {
            foreach ($matches[1] as $match) {
                $param['comment'] = str_replace($match, str_replace($this->base_url, '', $match), $param['comment']);
            }
        }
        if (preg_match_all('#<[^>]*=["\']([^"\']*/static/res/.+?\.[^"\']*)["\'][^>]*>#i', $param['comment'], $matches)) {
            foreach ($matches[1] as $match) {
                $param['comment'] = str_replace($match, str_replace($this->base_url, '', $match), $param['comment']);
            }
        }
        $rowCount = Model::update('comment', $param, ['id' => $param['id']]);

        // 修改媒体状态
        $paths = [0 => [], 1 => [], 2 => []];
        if (preg_match_all('#<[^>]*=["\']([^"\']*/static/upload/.+?\.[^"\']*)["\'][^>]*>#i', $row['comment'], $matches)) {
            foreach ($matches[1] as $match) {
                if (is_file(IA_ROOT . str_replace($this->base_url, '', $match)))
                    $paths[1][] = str_replace($this->base_url, '', $match);
                else
                    $paths[2][] = str_replace($this->base_url, '', $match);
            }
        }
        if (preg_match_all('#<[^>]*=["\']([^"\']*/static/upload/.+?\.[^"\']*)["\'][^>]*>#i', $param['comment'], $matches)) {
            foreach ($matches[1] as $match) {
                if (is_file(IA_ROOT . str_replace($this->base_url, '', $match)))
                    $paths[0][] = str_replace($this->base_url, '', $match);
                else
                    $paths[2][] = str_replace($this->base_url, '', $match);
            }
        }
        $paths[1] && Model::update('media', ['status' => 1], ['path' => array_unique($paths[1])]);
        $paths[0] && Model::update('media', ['status' => 0], ['path' => array_unique($paths[0])]);
        $paths[2] && Model::update('media', ['status' => 2], ['path' => array_unique($paths[2])]);
        if ($rowCount) {
            // 清除文章缓存
            $this->clearCache($row['article_id']);
            $this->log(Util::tran('编辑评论'), Util::tran('编辑评论') . " {$row['author']} " . Util::tran('成功'), 0);
            Util::errMsg(['code' => 0, 'msg' => Util::tran('编辑评论成功')]);
        } else {
            $this->log(Util::tran('编辑评论'), Util::tran('没有改变') . " {$row['author']} " . Util::tran('信息'), 0);
            Util::errMsg(['code' => 1, 'msg' => Util::tran('没有改变信息')]);
        }
    }

    // 待审
    public function pending()
    {
        $param = Util::param(['id']);
        (empty($param) || !isset($param['id'])) && Util::errMsg(Util::tran('请选择数据'));

        // 待审数据记录日志
        $rowCount = Model::update('comment', ['status' => 1], ['id' => $param['id']]);
        if ($rowCount) {
            // 清除文章缓存
            $ids = (array)$param['id'];
            $ids = array_unique($ids);
            $ids = implode(',', $ids);
            $rows = Model::fetchAll("SELECT `id`, `article_id` FROM `comment` WHERE `id` IN ($ids) ORDER BY `id` DESC");
            $aids = array_map(function ($item) {
                return $item['article_id'];
            }, $rows);
            $this->clearCache($aids);
            $this->log(Util::tran('待审评论'), Util::tran('待审评论成功'), 0);
            Util::errMsg(['code' => 0, 'msg' => Util::tran('待审成功')]);
        } else {
            $this->log(Util::tran('待审评论'), Util::tran('待审评论失败'), 1);
            Util::errMsg(['code' => 1, 'msg' => Util::tran('待审失败')]);
        }
    }

    // 通过
    public function passed()
    {
        $param = Util::param(['id']);
        (empty($param) || !isset($param['id'])) && Util::errMsg(Util::tran('请选择数据'));

        // 通过数据记录日志
        $rowCount = Model::update('comment', ['status' => 0], ['id' => $param['id']]);
        if ($rowCount) {
            // 清除文章缓存
            $ids = (array)$param['id'];
            $ids = array_unique($ids);
            $ids = implode(',', $ids);
            $rows = Model::fetchAll("SELECT `id`, `article_id` FROM `comment` WHERE `id` IN ($ids) ORDER BY `id` DESC");
            $aids = array_map(function ($item) {
                return $item['article_id'];
            }, $rows);
            $this->clearCache($aids);
            $this->log(Util::tran('审核通过评论'), Util::tran('审核评论成功'), 0);
            Util::errMsg(['code' => 0, 'msg' => Util::tran('审核成功')]);
        } else {
            $this->log(Util::tran('审核通过评论'), Util::tran('审核评论失败'), 1);
            Util::errMsg(['code' => 1, 'msg' => Util::tran('审核失败')]);
        }
    }

    // 垃圾评论
    public function spam()
    {
        $param = Util::param(['id']);
        (empty($param) || !isset($param['id'])) && Util::errMsg(Util::tran('请选择数据'));

        // 垃圾评论数据记录日志
        $rowCount = Model::update('comment', ['status' => 2], ['id' => $param['id']]);
        if ($rowCount) {
            // 清除文章缓存
            $ids = (array)$param['id'];
            $ids = array_unique($ids);
            $ids = implode(',', $ids);
            $rows = Model::fetchAll("SELECT `id`, `article_id` FROM `comment` WHERE `id` IN ($ids) ORDER BY `id` DESC");
            $aids = array_map(function ($item) {
                return $item['article_id'];
            }, $rows);
            $this->clearCache($aids);
            $this->log(Util::tran('垃圾评论'), Util::tran('审核为垃圾评论成功'), 0);
            Util::errMsg(['code' => 0, 'msg' => Util::tran('审核为垃圾评论成功')]);
        } else {
            $this->log(Util::tran('垃圾评论'), Util::tran('审核为垃圾评论失败'), 1);
            Util::errMsg(['code' => 1, 'msg' => Util::tran('审核为垃圾评论失败')]);
        }
    }

    // 删除
    public function delete()
    {
        $param = Util::param(['id']);
        (empty($param) || !isset($param['id'])) && Util::errMsg(Util::tran('请选择数据'));

        // 如果有回复评论
        $ids = (array)$param['id'];
        $idStr = implode(',', $ids);
        $rows = Model::fetchAll("SELECT `id` FROM `comment` WHERE `pid` IN ($idStr)");
        foreach ((array)$rows as $row) {
            $ids[] = $row['id'];
        }

        $idStr = implode(',', $ids);
        $rows = Model::fetchAll("SELECT `article_id`, `comment` FROM `comment` WHERE `id` IN ($idStr)");
        $paths = [1 => [], 2 => []];
        $aids = [];
        $comNames = [];
        foreach ($rows as $row) {
            $aids[] = $row['article_id'];
            $comNames[] = mb_strimwidth(preg_replace('/\s+/sim', ' ', strip_tags($row['comment'])), 0, 60, '...', 'UTF-8');
            if (preg_match_all('#<[^>]*=["\']([^"\']*/static/upload/.+?\.[^"\']*)["\'][^>]*>#i', $row['comment'], $matches)) {
                foreach ($matches[1] as $match) {
                    if (is_file(IA_ROOT . str_replace($this->base_url, '', $match)))
                        $paths[1][] = str_replace($this->base_url, '', $match);
                    else
                        $paths[2][] = str_replace($this->base_url, '', $match);
                }
            }
        }

        // 删除数据记录日志
        $rowCount = Model::delete('comment', ['id' => array_unique($ids)]);
        if ($rowCount) {
            // 修改媒体状态
            $paths[1] && Model::update('media', ['status' => 1], ['path' => array_unique($paths[1])]);
            $paths[2] && Model::update('media', ['status' => 2], ['path' => array_unique($paths[2])]);
            // 清除文章缓存
            $this->clearCache(array_unique($aids));
            $this->log(Util::tran('删除评论'), Util::tran('删除评论') . " " . implode(' ', $comNames) . " " . Util::tran('成功'), 0);
            Util::errMsg(['code' => 0, 'msg' => Util::tran('删除成功')]);
        } else {
            $this->log(Util::tran('删除评论'), Util::tran('删除评论失败'), 1);
            Util::errMsg(['code' => 1, 'msg' => Util::tran('删除失败')]);
        }
    }

    // 删除缓存
    private function clearCache($ids = 0)
    {
        if ($ids) {
            $ids = (array)$ids;
            $ids = array_unique($ids);
            $idStr = implode(',', $ids);
            $rows = Model::fetchAll("SELECT `id`, `slug` FROM `article` WHERE `id` IN ($idStr)");
            $prefix = $this->base_url . ($this->lang === 'zh-CN' ? "/" : "/{$this->lang}/");
            foreach ($rows as $row) {
                $file_name = md5($prefix);
                $cache_file = IA_ROOT . '/mvc/tpl/' . substr($file_name, 0, 2) . '/' . $file_name . '.php';
                if (file_exists($cache_file))
                    unlink($cache_file);
                $file_name = md5($prefix . ($row['slug'] ? $row['slug'] : $row['id']) . '.html');
                $cache_file = IA_ROOT . '/mvc/tpl/' . substr($file_name, 0, 2) . '/' . $file_name . '.php';
                if (file_exists($cache_file))
                    unlink($cache_file);
                // 删除分页缓存
                $count = Model::fetchColumn("SELECT COUNT(*) FROM `comment` WHERE `pid`=0 AND `article_id`=:article_id AND `status`=0 ORDER BY `id` DESC", [':article_id' => $row['id']]);
                for ($i = 2; $i <= $count; $i++) {
                    $file_name = md5($prefix . ($row['slug'] ? $row['slug'] : $row['id']) . '/page-' . $i . '.html');
                    $cache_file = IA_ROOT . '/mvc/tpl/' . substr($file_name, 0, 2) . '/' . $file_name . '.php';
                    file_exists($cache_file) && unlink($cache_file);
                }
            }
        }
    }
}
